define(function(require, exports, module){
	//require('./login-regist.css');
	require("../../base/placeholder/placeholder.js");
	require("../../base/util/modal.button.js");
	require("../../base/util/core.js");
	require("../../base/util/validate.js");
	require('../../base/autocomplete/autocomplete.js');
	require('../../base/qrcode/qrcode.min.js');
	require('/static/css/poplogin-less.css');


	$.ajaxSetup({cache:false})
	

	function signupTpl(){
		/*
		<div id="signup" class="rl-modal ">
		  <div class="rl-modal-header">
		    <button type="button" class="rl-close" data-dismiss="modal" aria-hidden="true"></button>
		    <h1>
				<span data-fromto="signup:signin">登录</span>
				<span class="active-title">注册</span>
		    </h1>
		  </div>
		  <div class="rl-modal-body js-modal-body">
		    <form id="signup-form">
				<p class="rlf-tip-globle rlf-g-tip" id="signup-globle-error"></p>
				<div class="rlf-group proclaim-loc">
					<input  type="text" name="email" data-validate="email" class="ipt ipt-email" autocomplete="off" placeholder="请输入注册手机号/邮箱"/>
					<input style="display:none;" >
					<p class="rlf-tip-wrap"></p>
				</div>

				<div class="rlf-group proclaim-loc js-proclaim-on hide">
					<a href="javascript:void(0)" hidefocus="true" class="proclaim-btn js-proclaim icon-show-pw is-pwd" tabindex="-1"></a>
					<input type="password" name="password" data-validate="password" class="ipt ipt-pwd js-pass-pwd" placeholder="6-16位密码，区分大小写，不能用空格" maxlength="16" autocomplete="off"/>
			        <!--ie8 hack-->
			        <input type="text" name="password" data-validate="password" class="ipt ipt-pwd js-txt-pwd" placeholder="6-16位密码，区分大小写，不能用空格" maxlength="16" autocomplete="off"/>
			        <p class="rlf-tip-wrap"></p>
				</div>

				<div class="rlf-group clearfix">
				    <input type="text" name="verify" class="ipt ipt-verify l" maxlength="4" placeholder="请输入验证码">
				    <a href="javascript:void(0)" hidefocus="true" class="verify-img-wrap js-verify-refresh"></a>
				    <a href="javascript:void(0)" hidefocus="true" class="icon-refresh js-verify-refresh"></a>
					<p class="rlf-tip-wrap"></p>
				</div>
				<div class="rlf-group clearfix">
					<input  type="button" id="signup-btn" value="注册" hidefocus="true" class="btn-red btn-full r"/>
				</div>
		    </form>
		  </div>
		  <div class="rl-model-footer">
		  	<div class="pop-login-sns clearfix">
		  		<span class="l">其他方式登录</span>
		  		<a href="javascript:void(0)" hidefocus="true" data-login-sns="/passport/user/tplogin?tp=weibo" class="pop-sns-weibo r"><i class="icon-weibo"></i></a>
		  		<a href="javascript:void(0)" hidefocus="true" data-login-sns="/passport/user/tplogin?tp=qq" class="pop-sns-qq r"><i class="icon-qq"></i></a>
		  		<a href="javascript:void(0)" hidefocus="true" data-login-sns="/passport/user/tplogin?tp=weixin" class="pop-sns-weixin r"><i class="icon-weixin"></i></a>
		  	</div>

		  </div>
		</div>
		 */
	}
	function signinTpl(){
		/*
		<div id="signin" class="rl-modal">
		  <div class="rl-modal-header">
		    <h1>
				<span class="active-title">登录</span>
				<span data-fromto="signin:signup">注册</span>
		    </h1>
		    <button type="button" class="rl-close" data-dismiss="modal" hidefocus="true" aria-hidden="true"></button>
		  </div>
		  <div class="rl-modal-body">
		  	<div class="clearfix">
				<div class="l-left-wrap l">
					<form id="signup-form" autocomplete="off">
						<p class="rlf-tip-globle " id="signin-globle-error"></p>
						<div class="rlf-group">
							<input type="text" value="" name="email" data-validate="email" autocomplete="off" class="ipt ipt-email js-own-name" placeholder="请输入登录手机号/邮箱"/>
							<p class="rlf-tip-wrap"></p>
						</div>
						<div class="rlf-group proclaim-loc js-proclaim-on ">
							<a href="javascript:void(0)" hidefocus="true" class="proclaim-btn js-proclaim icon-show-pw is-pwd" tabindex="-1"></a>
							<input type="password" name="password"  data-validate="password" class="ipt ipt-pwd js-pass-pwd" placeholder="6-16位密码，区分大小写，不能用空格" maxlength="16" autocomplete="off"/>
					        <!--ie8 hack-->
					        <input type="text" name="password"  data-validate="password" class="ipt ipt-pwd js-txt-pwd" placeholder="6-16位密码，区分大小写，不能用空格" maxlength="16" autocomplete="off"/>
					        <p class="rlf-tip-wrap"></p>
						</div>
						
						<div class="rlf-group js-verify-row clearfix" style="display: none">
						    <input type="text" name="verify" class="ipt ipt-verify l" maxlength="4" placeholder="请输入验证码">
						    <a href="javascript:void(0)" class="verify-img-wrap js-verify-refresh"></a>
				    		<a href="javascript:void(0)" class="icon-refresh js-verify-refresh"></a>
							<p class="rlf-tip-wrap"></p>
						</div>
						<div class="rlf-group rlf-appendix clearfix">
							<label for="auto-signin" class="rlf-autoin l" hidefocus="true"><input type="checkbox" checked="checked" class="auto-cbx" id="auto-signin">下次自动登录</label>
							<a href="/user/newforgot" class="rlf-forget r" target="_blank" hidefocus="true">忘记密码 </a>
						</div>
						<div class="rlf-group clearfix">
							<input  type="button" id="signin-btn" value="登录" hidefocus="true" class="btn-red btn-full"/>
						</div>
				    </form>
				</div>
		  	</div>
		  </div>
		  <div class="rl-model-footer">
			<div class="pop-login-sns clearfix">
				<span class="l">其他方式登录</span>
				<a href="javascript:void(0)" hidefocus="true" data-login-sns="/passport/user/tplogin?tp=weibo" class="pop-sns-weibo r mr60"><i class="icon-weibo"></i></a>
				<a href="javascript:void(0)" hidefocus="true" data-login-sns="/passport/user/tplogin?tp=qq" class="pop-sns-qq r"><i class="icon-qq"></i></a>
				<a href="javascript:void(0)" hidefocus="true" data-login-sns="/passport/user/tplogin?tp=weixin" class="pop-sns-weixin r"><i class="icon-weixin"></i></a>
			</div>
			 <div class="erweima js-clickToShowDialog"></div>
		  </div>
		</div>
		*/
	}

	function erweimaTpl(){
		/*
		  
		<div id="signin" class="rl-modal ">
		  <div class="rl-modal-header">
		    <button type="button" class="rl-close" data-dismiss="modal" aria-hidden="true"></button>
		    <h1>
				<span class="active-title">登录</span>
				<span data-fromto="signin:signup">注册</span>
		    </h1>
		  </div>
		  <div class="rl-modal-body">
		    <form id="signup-form">
			
				<div class="rlf-group proclaim-loc js-proclaim-on">
					<div class="qrcode" id="qrcode">
						<div class="hide qrcode-bk-scand">
							<div class="qrcode-inner"></div>
							<div class="qrcode_state_scaned"></div>
						</div>
						<div class="hide qrcode-bk-validate">
							<div class="qrcode-inner"></div>
							<div class="qrcode_state_validate js-refresh"></div>
						</div>
					</div>
					<p class="qrcode_title">扫描二维码登录慕课网</p>
					<p class="qrcode_mark">请使用新版 <a target="_blank" href="http://www.imooc.com/mobile/app" class="color-red">慕课网手机APP</a> 扫码完成登录</p>
				</div>
				
		    </form>
		  </div>
		  <div class="rl-model-footer">
		  	
 				<div class="pcLogin js-clickToSignin" data-fromto="signup:signin"></div>
		  </div>
		</div>
		 */
	}

	function phoneVerityTpl(){
		/*
		  
		<div id="signin" class="rl-modal ">
		  <div class="rl-modal-header">
		    <button type="button" class="rl-close" data-dismiss="modal" aria-hidden="true"></button>
		    <h1>
				<span data-fromto="signup:signin">登录</span>
				<span  class="active-title">注册</span>
		    </h1>
		  </div>
		  <div class="rl-modal-body phoneVerityBox">
		    <form id="signup-form">
				<p class="title">填写短信验证码密码完成注册</p>
				<p class="subtitle">短信验证码已发送至<span class="color-red js-phoneNumber"></span></p>
				<p class="rlf-tip-globle " id="signin-globle-error"></p>
				<div class="rlf-group pr">
					<input type="text" id="js-phoneVerity" class="ipt ipt-pwd" placeholder="请输入短信验证码" maxlength="4" autocomplete="off"/>
					<p class="reSend pa ">重新发送<span class="js-second">60</span></p>
					<p class="rlf-tip-wrap color-red" id="error-phoneVerity"></p>
				</div>
			

				<div class="rlf-group proclaim-loc js-pwdWrap js-proclaim-on ">
					<a href="javascript:void(0)" hidefocus="true" class="proclaim-btn js-V-proclaim icon-show-pw is-pwd" tabindex="-1"></a>
					<input type="password" id="js-password" name="password"  data-validate="password" class="ipt ipt-pwd js-pass-pwd" placeholder="6-16位密码，区分大小写，不能用空格" maxlength="16" autocomplete="off"/>
			        <!--ie8 hack-->
			        <input type="text" name="password"  data-validate="password" class="ipt ipt-pwd js-txt-pwd" placeholder="6-16位密码，区分大小写，不能用空格" maxlength="16" autocomplete="off"/>
			        <p class="rlf-tip-wrap color-red" id="error-password"></p>
				</div>


				<div class="rlf-group clearfix">
					<input  type="button" id="submit-btn" value="提交" hidefocus="true" class="btn-red btn-full r"/>
				</div>
				<p class="backNotify js-back"  data-fromto="signin:signup">返回修改手机号 </p>
		    </form>
		  </div>
		 
		</div>
		 */

	}

	function registerFinishedTpl(){
		/*
		  
		<div id="signin" class="rl-modal ">
		  <div class="rl-modal-header">
		    <button type="button" class="rl-close" data-dismiss="modal" aria-hidden="true"></button>
		    <h1>
				<span data-fromto="signup:signin">登录</span>
				<span  class="active-title">注册</span>
		    </h1>
		  </div>
		  <div class="rl-modal-body phoneVerityBox">
		    <form id="signup-form">
				<p class="rlf-tip-globle " id="signin-globle-error"></p>
				<div class="user_header"></div>
				<p class="title">恭喜你！帐号注册成功</p>
				<p class="subtitle">可以通过 <span class="color-red js-account"></span>登录慕课网</p>
				<div class="rlf-group clearfix finished_wrap">
					<input  type="button" value="完成[5]" hidefocus="true" class="js-finishSecond btn-red btn-finished " id="js-finshed"/>
				</div>
		    </form>
		  </div>
		 
		</div>
		 */

	}

    
	var interval;
	var g_vals;
	var g_res;


    var tpl = {
  		signup:signupTpl,
		signin:signinTpl,
		erweima:erweimaTpl,
		phoneVerity:phoneVerityTpl,
		registerFinished:registerFinishedTpl
	}


	function getTpl(m){
		var r=/\/\*([\S\s]*?)\*\//m,
			m=r.exec(tpl[m].toString());
		return m&&m[1]||m;
	}

    $('body').on('blur', '#signin .js-pass-pwd', function (){
        var value = $.trim( this.value );
        $('#signin').find('.js-txt-pwd').val( value );
    })
    
    $('body').on('blur', '#signin .js-txt-pwd', function (){
        var value = $.trim( this.value );
        $('#signin').find('.js-pass-pwd').val( value );
    })
    
    $('body').on('blur', '#signup .js-pass-pwd', function (){
        var value = $.trim( this.value );
        $('#signup').find('.js-txt-pwd').val( value );
    })
    
    $('body').on('blur', '#signup .js-txt-pwd', function (){
        var value = $.trim( this.value );
        $('#signup').find('.js-pass-pwd').val( value );
    })
    
	var winsns=(function(){
		var o={};

		function clearPrev(){//dereference
			for(var key in o){
				if(key.indexOf("/user")>-1){
					o[key].close&&o[key].close();
					o[key]=null;
					delete o[key];
				}
			}
		}

		return {
			open:function(url){
				var l,t;
				if(o[url]&&o[url].closed===false){
					o[url].focus&&o[url].focus();
					return ;
				}
				clearPrev();
				l=(screen.width-650)/2,
				t=(screen.height-400)/2;
				(o[url]=window.open(url+"&referer="+window.location.protocol+"//"+window.location.hostname, '_blank', 'toolbar=no, directories=no, status=no, menubar=no, width=650, height=500, top='+t+', left='+l)).focus();
			},
			clear:clearPrev
		}
	})();

	function checkPassword(value){
	var legal = /^[\w~`!@#$%&*()_+<>?:"'+*\/\-\^\\\][{}]{6,16}$/;
		if(legal.test(value)){
			return true;

		}
		else{
			return false;
		}
	}

	function checkPhoneVerity(value){
	var legal = /^\d{4}$/;
		if(legal.test(value)){
			return true;

		}
		else{
			return false;
		}
	}

	$(function(){
		$(document).on("click","[data-fromto]",function(e){
			e.preventDefault();
			var d=$(this).attr("data-fromto").split(":");
			$("#"+d[0]).modal("hide");
			d[1]&&m[d[1]]();
		})
		.on("click","[data-login-sns]",function(){
			winsns.open($(this).attr("data-login-sns"));
		})
		.on("click",".j-chgvtfimg",function(){
			var $p=$(this).prev("img");
			$p.attr("src",$p.attr("src").replace(/\?\d+|$/,"?"+(new Date()).getTime()));
		})
		.on("click",".js-clickToShowDialog",function(){
			
			$(".rl-modal-body").html(getTpl("erweima"));
			//var guid = new GUID();
　　		//alert(guid.newGUID());　

			var code = new GUID().newGUID();
			var codeStr =  "http://www.imooc.com?ma="+code;
			$('#qrcode').qrcode({width: 150,height: 150,text: codeStr});
			loopScan(code);
		 	
		})
		.on("click",".js-clickToSignin",function(){
			$(".modal-backdrop").click();
			var d=$(this).attr("data-fromto").split(":");
			$("#"+d[0]).modal("hide");
			d[1]&&m[d[1]]();
			clearInterval(interval);
		})
		.on("click",".js-refresh",function(){
			$(".rl-modal-body").html(getTpl("erweima"));
			$(this).addClass("hide");
			var code = new GUID().newGUID();
			var codeStr =  "http://www.imooc.com?ma="+code;
			$('#qrcode').qrcode({width: 150,height: 150,text: codeStr});
			loopScan(code);
		})
		.on("blur",".phoneVerityBox #js-phoneVerity",function(){
			if(checkPhoneVerity($(this).val())){
				$("#error-phoneVerity").empty();
			}
			else{
				if($(this).val().length ==0 ){
					$("#error-phoneVerity").html("验证码不能为空！");
				}
				else{
					$("#error-phoneVerity").html("验证码错误！");
				}
				
			}
		})
		.on("blur",".phoneVerityBox #js-password",function(){
			if(checkPassword($(this).val())){
				$("#error-password").empty();
			}
			else{
				if($(this).val().length ==0 ){
					$("#error-password").html("密码不能为空！");
				}else{
					$("#error-password").html("请输入6-16位密码，区分大小写，不能使用空格！");
				}
			}
		})
		.on("click",".phoneVerityBox .js-back",function(e){
			$(".modal-backdrop").click();
			clearInterval(interval);
			e.preventDefault();
			var d=$(this).attr("data-fromto").split(":");
			$("#"+d[0]).modal("hide");
			d[1]&&m[d[1]]();

		})
		.on("click","#js-finshed",function(e){
			
			window.location.href="/user/setprofile"
		
		})
		.on("blur",".ipt-email",function(e){
			//$(this).val($.trim($(this).val()) );
			$(this).val($(this).val().replace(/[ ]/g,"")); 
		})
		.on("click",".ipt",function(e){
			//$(this).val($.trim($(this).val()) );
			$("#signin-globle-error").empty();
			$("#signup-globle-error").empty();

		}) 

		.on("click",".phoneVerityBox .js-reSend",function(){
			$.ajax({
			 	url:"/passport/user/phoneregister",
			 	data:g_vals,
	            method:"post",
				dataType:"json",
				success:function(data){
					//alert("手机号接口调用成功")
					if(data.status == 10001) {
						$(".rl-modal-body").html(getTpl("phoneVerity"));
						$(".js-phoneNumber").html(g_vals.number);
						var index = 60;
						clearInterval(interval);
						interval = setInterval(function(){
							$(".js-second").parent().removeClass("js-reSend");
							$(".js-second").parent().removeClass("active");
							$(".js-second").html(index);
							if(index<1){
								$(".js-second").parent().addClass("active");
								$(".js-second").parent().addClass("js-reSend");
								$(".js-second").html("");
								clearInterval(interval);

							}
							index--;
							
						},1000)
					}
					else{
						$("#signin-globle-error").addClass("rlf-tip-error").html(data.msg);
						if(data.status == 11001){
							$(".js-reSend").css("color","#B4B8BB");
							$(".js-reSend").css("cursor","default");
							$(".js-reSend").removeClass("active");
							$(".js-reSend").removeClass("js-reSend");
							$(".js-second").html("");
						}
					}
					// if(data.status == 90010) {
					// 	$("#signup-globle-error").addClass("rlf-tip-error").html(data.msg);
					// }else{

					// 	$(".rl-modal-body").html(getTpl("phoneVerity"));
					// 	$(".js-phoneNumber").html(g_vals.number);
					// 	var index = 60;
					// 	interval = setInterval(function(){
					// 		$(".js-second").parent().removeClass("js-reSend");
					// 		$(".js-second").parent().removeClass("active");
					// 		$(".js-second").html(index);
					// 		if(index<1){
					// 			$(".js-second").parent().addClass("active");
					// 			$(".js-second").parent().addClass("js-reSend");
					// 			$(".js-second").html("");
					// 			clearInterval(interval);

					// 		}
					// 		index--;
							
					// 	},1000)
					// }
					
				},
				error:function(){
					$("#signup-globle-error").addClass("rlf-tip-error").html("服务错误，稍后重试");
				},	
			})
		})

		.on("click","#submit-btn",function(){
			$('.phoneVerityBox #js-password').trigger("blur");
			$('.phoneVerityBox #js-phoneVerity').trigger("blur");
			if(checkPassword($("#js-password").val())&&checkPhoneVerity($("#js-phoneVerity").val())){
				var val ={
					number:$(".js-phoneNumber").html(),
					mobileverify:$("#js-phoneVerity").val(),
					password:$("#js-password").val(),
					type:1,
					referer:window.location.protocol+"//"+window.location.hostname,
				}
				$.ajax({
				 	url:"/passport/user/phoneregister",
				 	data:val,
                    method:"post",
					dataType:"json",
					success:function(res){
						if(res.status == 10001){

								g_res = res;
								imoocSSO.crossDomainAction(function(){
																	
									var index = 5;
									$(".rl-modal-body").html(getTpl("registerFinished"));
									interval=setInterval(function(){
										
										$(".js-account").html(g_vals.number);
										$(".js-finishSecond").val("完成["+index+"]");
										$(".js-account").html(g_vals.email);
										if(index<1){
											clearInterval(interval);
											window.location.href="/user/setprofile";

											//fireLogined(res.data.userInfo);

										};
										index--;
									},1000);
								})
								imoocSSO.setCrossDomainCookie(res['data']['url']);

						}else{
							$("#signin-globle-error").addClass("rlf-tip-error").html(res['msg']);
						}
						
					},
					error:function(res){
						$("#signup-globle-error").addClass("rlf-tip-error").html("服务错误，稍后重试");
					},

				})
			}
			else{
			}
		})

		$(document).delegate(".js-V-proclaim", "click", function(){ 
		
			pwdPass = $(".js-pass-pwd"),
			protxt = $(".js-txt-pwd"),
			proclaimBtn = $(".js-V-proclaim"),
			
			proclaimCode = function(){
				if(proclaimBtn.hasClass("is-pwd")){
					//明文
					var inpValue=pwdPass.val();
					protxt.val(inpValue);

					proclaimBtn.parent().removeClass("js-proclaim-on").addClass("js-proclaim-off");
					proclaimBtn.removeClass("is-pwd");
				
				}else{
					//密码
					var inpValue=protxt.val();
					pwdPass.val(inpValue);
					proclaimBtn.parent().removeClass("js-proclaim-off").addClass("js-proclaim-on");
					proclaimBtn.addClass("is-pwd");
				}
			};
			proclaimCode();
		}); 
		
	})


	function getToken(ops){
		$.ajax({
			url:"/passport/user/scancode",
			method:"post",
			dataType:"json",
			data:ops,
			success:function(res){
				imoocSSO.crossDomainAction(function(){
					window.location.reload();
				})
				imoocSSO.setCrossDomainCookie(res['data']['url'])
			},
			errir:function(error){
			}
		})
	}
	function loopScan(code){
		var index = 0;
		var _code = code;
		function scanCode(){
			if(index>=30){
				clearInterval(interval);
				$(".qrcode-bk-validate").removeClass("hide");
				$(".qrcode-bk-scand").addClass("hide");
			}else{
				$.ajax({
		            url:"/user/ScanCode",
		            method:"post",
		            data:{codeid: _code},
		            dataType:"json",
		            success:function(obj){
						//var obj = JSON.parse(data); 
						var status = obj.data[0]['status']
						if( status != 3) {
							if(status == 0){
								$(".qrcode-bk-scand").removeClass("hide");
								$(".qrcode-bk-validate").addClass("hide");
							}
							else{
								if(status == 1) {
									clearInterval(interval);
									getToken({
										keyid: obj.data[0]['keyid'],
									 	uid: obj.data[0]['uid'],
										codeid: _code,
									 });
									///passport/user/scancode
					             // {"result":0,"data":[{"status":"0","kyeid":"8a461c0046ffc97fa75df66372c9a51f"}],"msg":1000}
								}
								if(status == 2) {
									$(".qrcode-bk-scand").addClass("hide");
									$(".qrcode-bk-validate").addClass("hide");
								}
							}
						}

		            },
		            error:function(data){
		            }
		        })
			}
	        index++;
		}
		interval= setInterval(scanCode, 2000);
	}


	function showModal(p){
		var m;
		p=p||"signin";
		m=$("#"+p);
		if(!m.length){
			$("body").append(getTpl(p));
			m=$("#"+p);
			m.on("shown",function(){
				$(this).find("form")[0].reset();
				$(this).find("input").placeholder();
			});
		}
		m.modal("show");

	}

	// 是否需要验证码
	var loginWithCode = false;
	var verifyLoad = false;

	

	var showLoginVerify = function(){
		loginWithCode = true;
		$('#signup-form').find('.js-verify-row').show();
	}; 

	var m={
		signin:function(){
			var tpl=getTpl("signin");
			return function(){
				var m=$("#signin");
				if(m.length) m.remove();
				$("body").append(getTpl("signin"));
				if(typeof(ownName) !== "undefined"){$(".js-own-name").val(ownName)};
				m=$("#signin");
				m.on("shown",function(){
					clearInterval(interval);
					$(this).find("form").validateSetup({
						fields:{
							// email: {
							// 	rules: [{

							// 	}]
							// },
							password:{
								rules:[function(cb,v){
						
									if(!loginWithCode){
										if(!verifyLoad){
											verifyLoad = true;
		                                    $.get( imoocSSO.checkVerifyUrl,"username="+$('[name="email"]').val(), function(data){
		                                        if(data.status == 10001){
		                                            showLoginVerify();
		                                        }
		                                    },"json");
	                                    }
									}else{
										showLoginVerify();
									}
									

									if(!v){
										return "密码不能为空！";
									}else if(v.length < 6){
										return "密码长度不能少于6位！"
									}
								}],
								keyup:function(e){
									if(e.keyCode=="13"){
										$("#signin-btn").trigger("click");
									}
									else{
										$(this).validate();
									}

								}
							},
							verify: {
								rules:[
								{
									rule: function(cb, v){
										if(!loginWithCode) return true;
										if(!v) {
											return "验证码不能为空！";
										}else if(v.length != 4){
											return "验证码错误";
										}
                                        return $.ajax({
                                            url:imoocSSO.checkVerifyCode,
                                            method:"post",
                                            data:{verify: v},
                                            dataType:"json",
                                            success:function(data){
                                                if(data.status == 10001){
                                                    cb();
                                                }
                                                else{
                                                    cb(data.msg)
                                                }
                                            }
                                        })
									}
								}
								],
								keyup: (function(){
									var interval=300,timer;
									return function(e){
										var $this=$(this),
											val = $.trim($this.val());

										if(timer) clearTimeout(timer);
										timer=setTimeout(function(){
											$this.validate(e);
										},interval);
									}
								})(),
								blur: function(e){
									/*$(this).siblings(".rlf-tip-wrap").find("span").hide();*/
									$(this).validate(e);
								}/*,
								focus: function(){
									$(this).siblings(".rlf-tip-wrap").find("span").show();
								}*/
							}
						},
						onerror:function(e){
							var $t,$d;
							if(e._relateField&&e.tip){
								$t=$(e._relateField);
								$t.addClass("ipt-error").siblings(".rlf-tip-wrap").html(e.tip).addClass("rlf-tip-error");
								($d=$t.data("placeholder-textinput"))&&$d.addClass("ipt-error");
							}
							$("#signin-globle-error").removeClass("rlf-tip-error").empty();
						},
						onvalid:function(e){
							var $t,$d;
							if(e._relateField){
								$t=$(e._relateField);
								$t.removeClass("ipt-error").siblings(".rlf-tip-wrap").removeClass("rlf-tip-error").empty();
								($d=$t.data("placeholder-textinput"))&&$d.removeClass("ipt-error");
							}
							$("#signin-globle-error").removeClass("rlf-tip-error").empty();
						}
					});


					$("#signin-btn").button({loadingText:"正在登录..."})
					.on("click",function(){
						var $this=$(this);
						var signInForm=$('#signup-form');
						if($this.hasClass("disabled")){ return;}
						$this.button("loading");
						$this.closest("form").validate({
							success:function(vals){
								var remember=$("#auto-signin")[0].checked?"1":"0",
									params = {
										username:vals.email,
										password:vals.password,
										remember:remember
									};

								if(loginWithCode){
									params.verify = vals.verify;
								}
                                //sso方式登录
				                imoocSSO.login({
				                    data:params,
				                    success:function(data){
				                    	data.data={userInfo:""}
				                        if(data.status==10001){
				                            fireLogined(data.data.userInfo);
				                            return ;
				                        }
				                        else if(data.status==900001){
				                            window.location.href="/user/userfrozen";
				                            return ;
				                        }
				                        else if(data.status == 10005||data.status == 10007){ // 需要出验证码
				                            showLoginVerify();
				                        }
				                        $("#signin-globle-error").addClass("rlf-tip-error").html(data.msg);

				                        if(loginWithCode){
				                            refreshVerifyCode();
				                            signInForm.find('.ipt-verify').val('');
				                        }
				                        //$("#signin-btn").button("reset");
				                    },
				                    error:function(){
				                        $("#signin-globle-error").addClass("rlf-tip-error").html("服务错误，稍后重试");
				                    },
				                    complete:function(){
				                        $("#signin-btn").button("reset");
				                    }
				                })

								// $.ajax({
								// 	url:"/user/login",
								// 	data: params,
								// 	method:"post",
								// 	dataType:"json",
								// 	success:function(data){
								// 		if(data.status===1){
								// 			fireLogined(data.data.userInfo);
								// 			return ;
								// 		}
								// 		else if(data.status==5){
								// 			window.location.href="/user/userfrozen";
								// 			return ;
								// 		}
								// 		else if(data.status == 9){ // 连续三次登陆失败
								// 			showLoginVerify();
								// 		}
								// 		$("#signin-globle-error").addClass("rlf-tip-error").html(data.msg);

								// 		if(loginWithCode){
								// 			refreshVerifyCode();
								// 			signInForm.find('.ipt-verify').val('');
								// 		}
								// 		//$("#signin-btn").button("reset");
								// 	},
								// 	error:function(){
								// 		$("#signin-globle-error").addClass("rlf-tip-error").html("服务错误，稍后重试");
								// 	},
								// 	complete:function(){
								// 		$("#signin-btn").button("reset");
								// 	}

								// });

							},
							error:function(){
								if(signInForm.find('.ipt-verify').val()){
									refreshVerifyCode();

									var interval=500,valTimer;

									if(valTimer) clearTimeout(valTimer);
									valTimer=setTimeout(function(){
										signInForm.find('.ipt-verify').val('');
									},interval)
								}

								setTimeout('$("#signin-btn").button("reset");',1);
							}
						})
					});
					//placeholder  init;
					$(this).find("input").placeholder();

					proclaimCode = function(){
						if(proclaimBtn.hasClass("is-pwd")){
							//明文
							var inpValue=pwdPass.val();
							protxt.val(inpValue);

							proclaimBtn.parent().removeClass("js-proclaim-on").addClass("js-proclaim-off");
							proclaimBtn.removeClass("is-pwd");
						
						}else{
							//密码
							var inpValue=protxt.val();
							pwdPass.val(inpValue);

							proclaimBtn.parent().removeClass("js-proclaim-off").addClass("js-proclaim-on");
							proclaimBtn.addClass("is-pwd");
							
						}
					};

					var signInForm = $(this),
					pwdPass = $(".js-pass-pwd"),
					protxt = $(".js-txt-pwd"),
					proclaimBtn = $(".js-proclaim"),
					refreshVerifyCode = function(){
						signInForm.find('.verify-img').attr('src', imoocSSO.verifyCodeUrl+"?t=" + new Date().getTime());
					},
					proclaimCode = function(){
						if(proclaimBtn.hasClass("is-pwd")){
							//明文
							var inpValue=pwdPass.val();
							protxt.val(inpValue);

							proclaimBtn.parent().removeClass("js-proclaim-on").addClass("js-proclaim-off");
							proclaimBtn.removeClass("is-pwd");
						
						}else{
							//密码
							var inpValue=protxt.val();
							pwdPass.val(inpValue);

							proclaimBtn.parent().removeClass("js-proclaim-off").addClass("js-proclaim-on");
							proclaimBtn.addClass("is-pwd");
							
						}
					};

					signInForm.find('.verify-img-wrap').append(
						$('<img class="verify-img"/>')
					);

					refreshVerifyCode();

					signInForm.on('click', '.js-verify-refresh', function(e){
						refreshVerifyCode();
					});
					signInForm.on('click', '.js-proclaim', function(e){
						e.stopPropagation();
						proclaimCode();
					});


				}).on("hidden",function(){
					$(this).remove();
					winsns.clear();
				});
				m.modal("show");
			}
		}(),
		signup:function(){
			var tpl=getTpl("signup");
			return function(){
				var m=$("#signup");
				if(m.length) m.remove();
				$("body").append(getTpl("signup"));
				m=$("#signup");
				m.on("shown",function(){
					$(this).find("form").validateSetup({
						fields:{
							email:{
								rules:[{
									rule:function(cb,v){
										var url="/passport/user/checkphone"
										,data= {phone:v};
										if(v.indexOf("@")!=-1){
											url=imoocSSO.checkUserName;
											data = {username:v};
										}
										return $.ajax({
                                            url:url,
                                            method:"get",
                                            data:data,
                                            dataType:"json",
											success:function(data){
												if(data.status==10001){
													cb();
												}
												else{

													cb(data.msg)
												}
											}
										})	
									}
								}],
								keyup:(function(cb,v){
									return function(e){
										var value = $(e.currentTarget).val();
										if(value.indexOf("@")>=0){
											//$(e.currentTarget).attr("name","email");
											if($(".js-pass-pwd").is(':hidden')){
												$(".js-pass-pwd").val("");
											}
											
											$(".js-pass-pwd").show().parent().removeClass('hide');
										}
										else{
											//$(e.currentTarget).removeAttr("name");
											$(".js-pass-pwd").removeAttr("data-validate");
											$(".js-pass-pwd").hide().parent().addClass('hide');
										}
									}
								})(),
								blur:function(e){
									$(this).validate(e);
								},
								focus:function(){
									$(".ipt-email").autocomplete();
								}
							},
							password:{
								blur:function(e){
									//rgrTip.empty();
									$(this).validate(e);

									if(!proclaimBtn.hasClass("is-pwd")){
										var inpValue=protxt.val();
										pwdPass.val(inpValue);								
									}

								}
								// focus:function(){
								// 	rgrTip.html("6-16位密码，区分大小写，不能使用空格");
								// },
								// onvalid: function(e) {
								// 	$('input[name="cfmpwd"]', this.form).validate(e);
								// }
							},

							// nick:{
							// 	rules:[{
							// 		rule:function(cb,v){
							// 			return $.ajax({
       //                                      url:imoocSSO.checkNickName,
       //                                      method:"get",
       //                                      data:{nickname:v},
       //                                      dataType:"json",
							// 				success:function(data){
							// 					if(data.status==10001){
							// 						cb();
							// 					}
							// 					else{
							// 						cb(data.msg)
							// 					}
							// 				}
							// 			})
							// 		}
							// 	}],
							// 	blur:function(e){
							// 		//rgrTip.empty();
							// 		$(this).validate(e);
							// 	}
							// 	/*,
							// 	focus:function(){
							// 		rgrTip.html("2-18位中英文、数字或下划线");
							// 	}*/
							// },


							/*cfmpwd:{
								rules:[function(cb,v) {
									if(!v) {
										return "验证密码不能为空！";
									}
									if($('input[name="password"]',this.form).val() !== v) {
										return '两次密码不一致！';
									}
								}],
								blur:function(e){
									$(this).next(".rlf-tip-wrap").find("span").hide();
									$(this).validate(e);
								},
								focus:function(){
									$(this).next(".rlf-tip-wrap").find("span").show();
								}
							},*/
							verify: {
								rules:[
								{
									rule: function(cb, v){
										if(!v) {
											return "验证码不能为空！";
										}
										if(v.length != 4){
											return "验证码错误";
										}
										return $.ajax({
											url:imoocSSO.checkVerifyCode,
                                            method:"get",
                                            data:{verify: v},
                                            dataType:"json",
											success:function(data){
												if(data.status == 10001){
													cb();
												}
												else{
													cb(data.msg)
												}
											}
										})
									}
								}
								],
								keyup: (function(){
									var interval=300,timer;
									return function(e){
										var $this=$(this),
											val = $.trim($this.val());

										if(timer) clearTimeout(timer);
										timer=setTimeout(function(){
											$this.validate(e);
										},interval);
									}
								})(),
								blur: function(e){
									$(this).validate(e);
									
								}/*,
								focus: function(){
									rgrTip.html("请输入右侧图片内容");
								}*/
							}
						},
						onerror:function(e){
							var $t,$d;
							if(e._relateField&&e.tip){
								$t=$(e._relateField);
								$t.addClass("ipt-error").siblings(".rlf-tip-wrap").html(e.tip).addClass("rlf-tip-error");
								($d=$t.data("placeholder-textinput"))&&$d.addClass("ipt-error");
							}
						},
						onvalid:function(e){
							var $t,$d;
							if(e._relateField){
								$t=$(e._relateField);
								$t.removeClass("ipt-error").siblings(".rlf-tip-wrap").removeClass("rlf-tip-error").empty();
								($d=$t.data("placeholder-textinput"))&&$d.removeClass("ipt-error");
							}
							$("#signup-globle-error").removeClass("rlf-tip-error").empty();
						}
					});

					$(this).find("input").placeholder();

					$("#signup-btn").button({loadingText:"正在注册..."})
					.on("click",function(){
						var $this=$(this);
					    if($this.hasClass("disabled")){ return;}      
						$this.button("loading");
						if($this.closest("form").find("[name='email']").val().indexOf("@")==-1){
							$this.closest("form").find("[name='password']").val("11111111")
						}
						$this.closest("form").validate({
							success:function(vals){
								//if(value.indexOf("@")>=0){
								g_vals = vals;
								if(vals.email.indexOf("@")>=0){
					                imoocSSO.register({
					                    data:{
	                                        username:vals.email,
	                                        password:vals.password,
	                                        verify: vals.verify
	                                    },
	                                    success:function(data){
					                        data.data={userInfo:""}
					                        if(data.status==10001){
				                           		g_res = data;   
	                                    		//imoocSSO.crossDomainAction(function(){
													var index = 5;
													$(".rl-modal-body").html(getTpl("registerFinished"));
													interval=setInterval(function(){
														$(".js-account").html(g_vals.number);
														$(".js-finishSecond").val("完成["+index+"]");
														$(".js-account").html(g_vals.email);
														if(index<1){
															clearInterval(interval);
															window.location.href="/user/setprofile";
														};
														index--;
													},1000);
												// })
												// imoocSSO.setCrossDomainCookie(data['data']['url']);
					                        }

					                        $("#signup-globle-error").addClass("rlf-tip-error").html(data.msg);
					                        $("#signup-btn").val("注册").removeAttr("disabled").removeClass("disabled");

					                        // 重置验证码
					                        refreshVerifyCode();
					                        signUpForm.find('.ipt-verify').val('');


	                                    },
	                                    error:function(){
	                                    	$("#signup-btn").val("注册").removeAttr("disabled").removeClass("disabled");
	                                        $("#signup-globle-error").addClass("rlf-tip-error").html("服务错误，稍后重试");
	                                    },
	                                    complete:function(){
	                                        $("#signup-btn").button("reset");
	                                    }
					                })
								}else{
									var val = {
	                                        number:vals.email,
	                                        verify: vals.verify};

	                                g_vals = val;
									 $.ajax({
									 	url:"/passport/user/phoneregister",
									 	data:val,
	                                    method:"post",
										dataType:"json",
										success:function(data){
											 if(data.status == 10001){
												$(".rl-modal-body").html(getTpl("phoneVerity"));

												$(".js-phoneNumber").html(val.number);
												var index = 60;
													clearInterval(interval);

													interval = setInterval(function(){
													$(".js-second").parent().removeClass("js-reSend");
													$(".js-second").parent().removeClass("active");
													$(".js-second").html(index);
													if(index<1){
														$(".js-second").parent().addClass("active");
														$(".js-second").parent().addClass("js-reSend");
														$(".js-second").html("");
														clearInterval(interval);

													}
													index--;
													
												},1000)
											 }else{
												$("#signup-btn").val("注册").removeAttr("disabled").removeClass("disabled");
												$("#signup-globle-error").addClass("rlf-tip-error").html(data.msg);
											}
											
										},
										error:function(){
											$("#signup-btn").val("注册").removeAttr("disabled").removeClass("disabled");
											$("#signup-globle-error").addClass("rlf-tip-error").html("服务错误，稍后重试");
										},


									 })
								}


								// $.ajax({
								// 	url:"/user/register/",
								// 	data:{
								// 		username:vals.email,
								// 		password:vals.password,
								// 		nickname:vals.nick,
								// 		verify: vals.verify
								// 	},
								// 	method:"post",
								// 	dataType:"json",
								// 	success:function(data){
								// 		if(data.status===0){
								// 			fireLogined(data.data.userInfo,true);
								// 			return ;
								// 		}
								// 		$("#signup-globle-error").addClass("rlf-tip-error").html(data.msg);

								// 		// 重置验证码
								// 		refreshVerifyCode();
								// 		signUpForm.find('.ipt-verify').val('');
								// 	},
								// 	error:function(){
								// 		$("#signup-globle-error").addClass("rlf-tip-error").html("服务错误，稍后重试");
								// 	},
								// 	complete:function(){
								// 		$("#signup-btn").button("reset");
								// 	}
								// });

							},
							error:function(vals){
								if(signUpForm.find('.ipt-verify').val()){
									refreshVerifyCode();

									var interval=500,valTimer;

									if(valTimer) clearTimeout(valTimer);
									valTimer=setTimeout(function(){
										signUpForm.find('.ipt-verify').val('');
									},interval)
								}
								

								setTimeout('$("#signup-btn").button("reset")',1);
							}
						})
					});

					var signUpForm = $(this),
						pwdPass = $(".js-pass-pwd"),
						protxt = $(".js-txt-pwd"),
						proclaimBtn = $(".js-proclaim"),
						refreshVerifyCode = function(){
							signUpForm.find('.verify-img').attr('src', imoocSSO.verifyCodeUrl+"?t=" + new Date().getTime());
						},
						proclaimCode = function(){
							if(proclaimBtn.hasClass("is-pwd")){
								//明文
								var inpValue=pwdPass.val();
								protxt.val(inpValue);

								proclaimBtn.parent().removeClass("js-proclaim-on").addClass("js-proclaim-off");
								proclaimBtn.removeClass("is-pwd");
							
							}else{
								//密码
								var inpValue=protxt.val();
								pwdPass.val(inpValue);

								proclaimBtn.parent().removeClass("js-proclaim-off").addClass("js-proclaim-on");
								proclaimBtn.addClass("is-pwd");
								
							}
						};

					signUpForm.find('.verify-img-wrap').append(
						$('<img class="verify-img"/>')
					);

					refreshVerifyCode();

					signUpForm.on('click', '.js-verify-refresh', function(e){
						refreshVerifyCode();
					});
					signUpForm.on('click', '.js-proclaim', function(e){
						e.stopPropagation();
						proclaimCode();
					});

				}).on("hidden",function(){
					$(this).remove();
				});
				m.modal("show");
			}
		}()
	}

	var fireLogined=window.__fireLogined=window.__fireLogined||function(data,signup){
		var e=$.extend($.Event("logined.imooc"),{_data:data});
		$("#signin [data-dismiss],#signup [data-dismiss]").trigger("click");
		$(document).trigger(e);
		winsns.clear();

		if(e.isDefaultPrevented()){
			return ;
		}
		//default actions; can be prevent by call e.preventDefault method
		if(signup) {
			window.location.replace("/user/setprofile");
			return ;
		}
		var pathname=window.location.pathname,forward;

		forward="error,forget,logout,newforgot,userfrozen,sendresult,resetpasspage,resetpassword,checkaopenguser".split(",").join("|");
		forward=new RegExp("\\/(?:"+forward+")(?:\\/|$|\\?|#)");
		if(forward.test(pathname)){ //remove pathname=="/" index login
			window.location.replace("/course/list"); ///index
			return ;
		}
		window.location.reload();

	}

	//fireLogined();

	module.exports = {
        init : function(){
        	//$("body").append(getTpl("signin"));
        	m.signin();
        },
		signup:function(){
			m.signup();
		}
    };

});


